package com.muyu.payment.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.util.IdUtil;
import com.muyu.payment.domain.PaymentTransaction;
import com.muyu.payment.mapper.PaymentTransactionMapper;
import com.muyu.payment.service.PaymentTransactionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 交易记录服务实现类
 */
@Service
public class PaymentTransactionServiceImpl extends ServiceImpl<PaymentTransactionMapper, PaymentTransaction> 
        implements PaymentTransactionService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createTransaction(PaymentTransaction transaction) {
        // 生成交易编号
        String transactionNo = "T" + IdUtil.simpleUUID();
        Date now = new Date();
        String currentUser = "system"; // 这里应该从安全上下文中获取当前用户
        
        transaction.setTransactionNo(transactionNo);
        transaction.setStatus(0); // 处理中
        transaction.setCreateTime(now);
        transaction.setUpdateTime(now);
        transaction.setCreateBy(currentUser);
        transaction.setUpdateBy(currentUser);
        
        // 保存交易记录
        save(transaction);
        
        return transaction.getId();
    }

    @Override
    public PaymentTransaction getByTransactionNo(String transactionNo) {
        return lambdaQuery()
                .eq(PaymentTransaction::getTransactionNo, transactionNo)
                .one();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTransactionStatus(String transactionNo, Integer status, String channelResponse) {
        return lambdaUpdate()
                .eq(PaymentTransaction::getTransactionNo, transactionNo)
                .set(PaymentTransaction::getStatus, status)
                .set(channelResponse != null, PaymentTransaction::getChannelResponse, channelResponse)
                .set(PaymentTransaction::getNotifyTime, new Date())
                .set(PaymentTransaction::getUpdateTime, new Date())
                .update();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handleTransactionSuccess(String transactionNo, String channelTradeNo, String channelResponse) {
        // 更新交易状态为成功
        boolean updated = lambdaUpdate()
                .eq(PaymentTransaction::getTransactionNo, transactionNo)
                .set(PaymentTransaction::getStatus, 1) // 成功
                .set(PaymentTransaction::getChannelTradeNo, channelTradeNo)
                .set(PaymentTransaction::getChannelResponse, channelResponse)
                .set(PaymentTransaction::getNotifyTime, new Date())
                .set(PaymentTransaction::getUpdateTime, new Date())
                .update();

        if (updated) {
            // 这里可以添加其他业务逻辑，如发送交易成功通知等
            // ...
        }
        
        return updated;
    }
}
